package com.sicau.service.impl;

import com.sicau.dao.FileMapper;
import com.sicau.entity.dto.NoticePicture;
import com.sicau.entity.dto.TaskInfo;
import com.sicau.entity.pojo.vo.ResultVO;
import com.sicau.service.FileService;
import com.sicau.utils.CsvUtil;
import com.sicau.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    //定义文件保存的本地路径
    final String localPath = "D:\\File\\image\\";
    final String mappingPath = "/file/image/";

    @Autowired
    FileMapper fileMapper;

    @Override
    public ResultVO image(HttpServletRequest request) {
        try {
            //开始上传excel
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile("file");
            String location = multipartRequest.getParameter("location");
            NoticePicture noticePicture = new NoticePicture();

            String sourceName = multipartFile.getOriginalFilename(); // 原始文件名
            Long size = multipartFile.getSize();
            String fileType = sourceName.substring(sourceName.lastIndexOf("."));
            System.out.println("上传的文件名为:"+sourceName+"类型为:"+fileType+"大小："+size);

            //保存数据库的路径
            String sqlPath = null;

            //定义 文件名
            String filename = null;

            if (!multipartFile.isEmpty()) {
                //生成uuid作为文件名称
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //            //获得文件类型（可以判断如果不是图片，禁止上传）
        ////            String contentType = multipartFile.getContentType();
        ////            //获得文件后缀名
                String suffixName = sourceName.substring(sourceName.lastIndexOf(".")+1);

                System.err.println(suffixName);

                //得到 文件名
                filename = uuid + "." + suffixName;

                //创建图片对象
                sqlPath = mappingPath + filename;
                System.out.println(sqlPath);
                noticePicture.setPicPath(sqlPath);
                noticePicture.setPicName(sourceName);
                noticePicture.setLocation(location);


                String oldPath = fileMapper.queryImage(noticePicture).getPicPath();

                if(null != oldPath){
                    oldPath = localPath + oldPath.replaceAll(mappingPath,"");
                    System.err.println(oldPath);
                    FileUtils.deleteFile(oldPath);//删除本地原有文件
                }

                //文件保存路径
                multipartFile.transferTo(new File(localPath + filename));
                //将图片信息保存至数据库
                fileMapper.addImage(noticePicture);

                return new ResultVO(0,"上传图片成功");

            }else {
                return new ResultVO(-1,"文件接收错误");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return new ResultVO(-1,e.toString());
        }
    }

    @Override
    public ResultVO addTasks(HttpServletRequest request) {
        try {
            //创建一个通用的多部分解析器
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //判断 request 是否有文件上传,即多部分请求
            int pre = (int) System.currentTimeMillis();
            if (multipartResolver.isMultipart(request)) {
                //转换成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iter.next());
                    List<TaskInfo> taskInfos = CsvUtil.csvMappingObj(file);

                    fileMapper.addTasks(taskInfos);

                }
            }
            return new ResultVO(-1,"success");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVO(-1,e.toString());
        }
    }
}
